package com.kye.express.business.complete_information;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.name_certification.NameCertificationActivity;
import com.kye.express.databinding.ActivityCompleteInformationBinding;
import com.kye.express.utils.StringFormatUtils;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.user.User;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class CompleteInformationActivity extends BaseAppCompatActivity implements CompleteInformationContract.CompleteInformationView {

    private static final String KEY_PHONE = "KEY_PHONE";

    private ActivityCompleteInformationBinding mBinding;
    private CompleteInformationContract.CompleteInformationPresenter mPresenter;
    private Dialog mDialog;
    private User mUser;

    public static void startActivity(Context context, User user) {
        context.startActivity(
                new Intent(context, CompleteInformationActivity.class)
                        .putExtra(KEY_PHONE, user)
        );
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_complete_information);

        initEvent();
        initData();
    }

    private void initEvent() {
        setSupportActionBar(mBinding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        ToolbarManager.setToolbar(this, mBinding.toolbar);

        Observable.combineLatest(RxTextView.textChanges(mBinding.editTextCompleteInformationName), RxTextView.textChanges(mBinding.editTextCompleteInformationCompany), new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence charSequence, CharSequence charSequence2) throws Exception {
                return charSequence.length() >= 2 && charSequence2.length() >= 3;
            }
        })
                .compose(this.<Boolean>bindToLifecycleDestroy())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.buttonCompleteInformationSubmit.setEnabled(aBoolean);
                    }
                });

        RxView.clicks(mBinding.buttonCompleteInformationSubmit)
                .observeOn(Schedulers.computation())
                .map(new Function<Object, Object>() {
                    @Override
                    public Object apply(Object o) throws Exception {
                        String name = mBinding.editTextCompleteInformationName.getText().toString().trim();

                        if (StringFormatUtils.checkNameIsChinese(name)) {
                            return new IllegalArgumentException(getString(R.string.error_name_just_is_chinese));
                        }

                        if (name.contains(getString(R.string.common_mr)) || name.contains(getString(R.string.common_miss))) {
                            return new IllegalArgumentException(getString(R.string.error_name_cant_contains_appellation));
                        }

                        String company = mBinding.editTextCompleteInformationCompany.getText().toString().trim();
                        if (!company.contains(getString(R.string.common_company)) && !company.contains(getString(R.string.common_factory))) {
                            return new IllegalArgumentException(getString(R.string.error_company_need_contains));
                        }

                        return o;
                    }
                })
                .compose(this.bindToLifecycleDestroy())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof IllegalArgumentException) {
                            ToastManager.show(CompleteInformationActivity.this, ((IllegalArgumentException) o).getMessage());
                            return;
                        }

                        mPresenter.completeInformation(mUser, mBinding.editTextCompleteInformationName.getText().toString().trim(), mBinding.editTextCompleteInformationCompany.getText().toString().trim());
                    }
                });
    }

    private void initData() {
        mUser = (User) getIntent().getSerializableExtra(KEY_PHONE);
        mPresenter = new CompleteInformationContract.CompleteInformationPresenter();
        mPresenter.bind(this);
    }

    @Override
    public void onError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void onLoading() {
        mDialog = KyeProgressDialog.show(this, mDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mDialog);
    }

    @Override
    public void onSuccess() {
        NameCertificationActivity.startActivity(this);
        finish();
    }
}
